package com.zking.controller.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.zking.config.AlipayConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Controller
@RequestMapping("/pay")
@RequiredArgsConstructor
public class AlipayController {
    
    private final AlipayConfig alipayConfig;
    
    // 测试页面：/pay/alipay/index
    @GetMapping("alipay/index")
    public String index() {
        return "alipay/index";
    }
    
    // 支付详情页面，参数id为订单ID，自己调整
    @RequestMapping
    public String pay(@RequestParam Integer id, Model model) {
        // Mybatis根据id获取订单详情，然后转发到alipay支付页
        String tradeId = "（数据库查询结果）" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE) + id; // 就是id，注意是整数
        String tradeName = "订单名xxx";
        String tradeMoney = "6.66";
        String tradeDesc = "订单描述，商品描述xxx";
        // 设置参数
        model.addAttribute("tradeId", tradeId);
        model.addAttribute("tradeName", tradeName);
        model.addAttribute("tradeMoney", tradeMoney);
        model.addAttribute("tradeDesc", tradeDesc);
        // 转发-直接返回
        return "alipay/alipay";
    }
    
    // 支付宝支付结果回调路径：/pay/return，自己调整设置这里结果中的参数
    @RequestMapping("return")
    public String result(HttpServletRequest request, Model model) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                if (i == values.length - 1) {
                    valueStr.append(values[i]);
                } else {
                    valueStr.append(values[i]).append(",");
                }
            }
            params.put(name, valueStr.toString());
        }
        
        // 调用SDK验证签名
        boolean signVerified;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
        } catch (AlipayApiException ignored) {
            signVerified = false;
        }
        
        // 判断结果
        model.addAttribute("success", signVerified); // 是否支付成功
        if (signVerified) {
            // 商户订单号，就是你的订单ID
            String tradeId = request.getParameter("out_trade_no");
            // 支付宝交易号，支付宝生成的
            String tradeNo = request.getParameter("trade_no");
            // 付款金额
            String tradeMoney = request.getParameter("total_amount");
            // 设置参数
            model.addAttribute("tradeId", tradeId);
            model.addAttribute("tradeNo", tradeNo);
            model.addAttribute("tradeMoney", tradeMoney);
            // 支付成功跳转页面，改成自己的控制器路径，可以转发、重定向
            return "forward:/pay/alipay/result";
        } else {
            // 这里支付失败，你也可以定义另一个失败页面，这里用的都是result.jsp页面
            return "forward:/pay/alipay/result";
        }
    }
    
    // 结果界面，自己设置成功、失败的页面
    @RequestMapping("alipay/result")
    public String result() {
        return "alipay/result";
    }
    
    // 表单中的提交地址：pay/alipay/alipay.trade.page.pay
    @RequestMapping("alipay/alipay.trade.page.pay")
    public void pay(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        request.setCharacterEncoding("utf-8");
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(), alipayConfig.getMerchantPrivateKey(), "json", alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
        
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
        
        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = request.getParameter("WIDout_trade_no");
        // 付款金额，必填
        String total_amount = request.getParameter("WIDtotal_amount");
        // 订单名称，必填
        String subject = request.getParameter("WIDsubject");
        // 商品描述，可空
        String body = request.getParameter("WIDbody");
        
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        
        // 若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        // alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        // 请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        
        // 请求：获取到的结果来自阿里，配置要对
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        
        // 直接返回页面
        response.setContentType("text/html;charset=" + alipayConfig.getCharset());
        response.getWriter().println(result);
    }
}
